package v1

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"server/common"
	"server/internal"
	"server/internal/model"
	"server/pkg/app"
)

func CreateTask(c *gin.Context) {
	task := &model.TaskApi{}
	ShouldBind(task, c)
	task.OwnerID = SetUserInfo(c)
	group_str, err := json.Marshal(task.TaskGroups)
	if err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	task.TaskGroupStr = group_str
	task.Project.ID = task.ProjectID

	err = task.Create()
	if err != nil {
		c.String(http.StatusOK, err.Error())
		go CreateLog(c, "任务", "创建任务失败："+err.Error())
		return
	}
	c.String(http.StatusOK, "任务创建成功")
	go CreateLog(c, "任务", "创建任务："+task.Name)

}
func UpdateTask(c *gin.Context) {
	task := &model.TaskApi{}
	ShouldBind(task, c)
	task.OwnerID = SetUserInfo(c)
	group_str, err := json.Marshal(task.TaskGroups)
	if err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	task.TaskGroupStr = group_str
	task.Project.ID = task.ProjectID

	err = task.Update()
	if err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.String(http.StatusOK, "任务更新成功")
}

func ListTask(c *gin.Context) {
	tasks := &model.Task{}
	pages := &app.Page{}
	pages.Info(c)
	pipe_list, total := tasks.List(pages)
	c.JSON(http.StatusOK, gin.H{
		"total": total,
		"data":  pipe_list,
	})
}

func QueryTaskInfo(c *gin.Context) {
	task_api := &model.TaskApi{}
	QueryByName(&task_api.Task, c)
	if len(task_api.Name) == 0 {
		return
	}
	var total int64
	pages := &app.Page{}
	pages.Page = 1
	pages.Size = 10000
	if len(task_api.Task.TaskGroupStr) != 0 {
		err := json.Unmarshal([]byte(task_api.Task.TaskGroupStr), &task_api.TaskGroups)
		if err != nil {
			c.String(http.StatusOK, err.Error())
			return
		}
	}

	for i, tasks := range task_api.TaskGroups {
		for j, task := range tasks.Tasks {
			for k, testcase := range task.TestCases {
				testcase.InfoById()
				task_api.TaskGroups[i].Tasks[j].TestCases[k] = testcase
			}
		}
	}

	group_str, err := json.Marshal("{}")
	if err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}

	task_api.TaskGroupStr = group_str
	//for _, v := range task_api.TaskGroups {
	//	for _, task := range v.Tasks {
	//		id_list := task.TestCases
	//		testcases := model.QueryAllInById(id_list)
	//		fmt.Println(testcases)
	//	}
	//}
	c.JSON(http.StatusOK, gin.H{
		"data":  task_api,
		"total": total,
	})
}

func GetFatherMeau(souce *model.CaseMeau, key string) *model.CaseMeau {
	meau := &model.CaseMeau{}
	meau.QueryMd5(key)
	if souce.Md5 == "" {
		meau.Childs = souce.Childs
		souce = meau
	} else {
		meau.Childs = append(meau.Childs, *souce)
	}

	if *meau.FatherMD5 == "-1" {
		return meau
	}
	return GetFatherMeau(meau, *meau.FatherMD5)
}

// 定时任务开关
func TaskSwitch(c *gin.Context) {
	userinfo := GetUser(c)
	task := &model.Task{}
	ShouldBind(task, c)
	task.OwnerID = userinfo.ID
	err := task.SwitchCron()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
		return
	}
	if task.Switch == false {
		c.String(http.StatusOK, "关闭定时任务成功")
		go CreateLog(c, "任务", "关闭定时任务："+task.Name)
	} else {
		c.String(http.StatusOK, "开启定时任务成功")
		go CreateLog(c, "任务", "开始定时任务："+task.Name)
	}
}

func DeleteTask(c *gin.Context) {
	task := &model.Task{}
	userinfo := GetUser(c)
	name := c.Param("name") //获取url路径中参数

	task.Name = name
	task.Info()
	if task.Owner.Name != userinfo.Name {
		c.JSON(http.StatusOK, gin.H{
			"msg": "无权限",
		})
		go CreateLog(c, "任务", "删除任务"+task.Name+"失败："+"无权限")
		return
	}
	Delete(task, c)
	go CreateLog(c, "任务", "删除任务:"+task.Name)
}

func CopyTask(c *gin.Context) {
	task := &model.Task{}
	userinfo := GetUser(c)

	cy := &internal.Copy{}
	ShouldBind(cy, c)

	old_name := cy.Name
	task.Name = old_name
	task.Info()

	task.Name = cy.NewName
	task.OwnerID = userinfo.ID
	task.Model = model.Model{}
	err := task.Create()
	if err != nil {
		c.String(http.StatusOK, err.Error())
		go CreateLog(c, "任务", "复制任务:"+task.Name+"失败："+err.Error())
		return
	}
	c.String(http.StatusOK, "任务复制成功")
	go CreateLog(c, "任务", "复制任务"+old_name+"->"+task.Name)
}

func RunTask(c *gin.Context) {
	task := &model.Task{}
	userinfo := GetUser(c)
	ShouldBind(task, c)
	task.Info()

	histask := &model.HisTask{}
	histask.OwnerID = userinfo.ID
	histask.Name = task.Name
	histask.Branch = task.Branch
	histask.TaskGroupStr = task.TaskGroupStr
	histask.ProjectID = task.ProjectID
	histask.Param = task.Param
	histask.Status = common.RUNNING
	err := histask.Create()
	err = json.Unmarshal([]byte(histask.TaskGroupStr), &histask.TaskGroups)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		go CreateLog(c, "任务", "启动任务："+task.Name+"失败"+err.Error())
		return
	}
	go histask.Start()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		go CreateLog(c, "任务", "启动任务："+task.Name+"失败"+err.Error())
	} else {
		c.String(http.StatusOK, "任务"+task.Name+"运行成功")
		go CreateLog(c, "任务", "运行任务："+task.Name)
	}

}

func StopTask(c *gin.Context) {
	task := &model.Task{}
	histask := &model.HisTask{}
	ShouldBind(histask, c)
	histask.Status = common.STOPPED
	histask.Update()

	task.Info()
	err := task.Update()

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "停止任务失败",
		})
		go CreateLog(c, "任务", "停止任务"+task.Name+"失败："+err.Error())
		return
	}
	c.String(http.StatusOK, "停止任务成功")
	go CreateLog(c, "任务", "停止任务:"+task.Name)
}
